using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.ProductPlaninfo;
using WPFServices.Services.DomainService.Productinfo;
using WPFServices.Services.DomainService.BomInfo;
using WPFServices.Views.DomainViews.Productinfo;
using WPFServices.ViewModels.DomainViewModel.Productinfo;
using WPFServices.Views.DomainViews.BomInfo;
using WPFServices.ViewModels.DomainViewModel.BomInfo;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Net.Http;
using System.Text.Json;

namespace WPFServices.ViewModels.DomainViewModel.ProductPlaninfo
{
    public class AddProductPlanViewModel : BaseViewModel
    {
        private readonly ProductPlanService _productPlanService;
        private readonly ProductService _productService;
        private readonly BomService _bomService;
        private readonly HttpClient _httpClient;

        // 基础信息字段
        private string _planId;
        private string _planName;
        private int _fromType = 1; // 默认销售订单
        private string _productName;
        private string _specificationModel;
        private string _unit;
        private DateTime? _startTime;
        private DateTime? _needTime;
        private string _remark;

        // 右侧字段
        private string _productId;
        private string _productType;
        private int _planNums;
        private DateTime? _endTime;

        // 选中的产品
        private ProductDto _selectedProduct;
        private BomDto _selectedBom;

        // 附件
        private string _annex;
        private string _uploadedFileName;

        // 事件
        public event Action<bool> CloseWindow;

        public AddProductPlanViewModel()
        {
            _productPlanService = new ProductPlanService();
            _productService = new ProductService();
            _bomService = new BomService();
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://localhost:5264/api/");
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

            // 初始化命令
            SaveCommand = new RelayCommand(async _ => await SaveProductPlanAsync(), _ => CanSave());
            CancelCommand = new RelayCommand(_ => Cancel());
            SelectProductCommand = new RelayCommand(_ => SelectProduct());
            SelectBomCommand = new RelayCommand(_ => SelectBom(), _ => CanSelectBom());
            ClearBomCommand = new RelayCommand(_ => ClearBom());
            UploadFileCommand = new RelayCommand(async _ => await UploadFileAsync());

            // 初始化默认值
            PlanId = $"PLAN{DateTime.Now:yyyyMMddHHmmss}";
            StartTime = DateTime.Now;
            EndTime = DateTime.Now.AddDays(30);
            NeedTime = DateTime.Now.AddDays(25);
            FromType = 1; // 销售订单
        }

        #region 属性

        public string PlanId
        {
            get => _planId;
            set => SetProperty(ref _planId, value);
        }

        public string PlanName
        {
            get => _planName;
            set => SetProperty(ref _planName, value);
        }

        public int FromType
        {
            get => _fromType;
            set => SetProperty(ref _fromType, value);
        }

        public string ProductName
        {
            get => _productName;
            set => SetProperty(ref _productName, value);
        }

        public string SpecificationModel
        {
            get => _specificationModel;
            set => SetProperty(ref _specificationModel, value);
        }

        public string Unit
        {
            get => _unit;
            set => SetProperty(ref _unit, value);
        }

        public DateTime? StartTime
        {
            get => _startTime;
            set => SetProperty(ref _startTime, value);
        }

        public DateTime? NeedTime
        {
            get => _needTime;
            set => SetProperty(ref _needTime, value);
        }

        public string Remark
        {
            get => _remark;
            set => SetProperty(ref _remark, value);
        }

        public string ProductId
        {
            get => _productId;
            set => SetProperty(ref _productId, value);
        }

        public string ProductType
        {
            get => _productType;
            set => SetProperty(ref _productType, value);
        }

        public int PlanNums
        {
            get => _planNums;
            set => SetProperty(ref _planNums, value);
        }

        public DateTime? EndTime
        {
            get => _endTime;
            set => SetProperty(ref _endTime, value);
        }

        public ProductDto SelectedProduct
        {
            get => _selectedProduct;
            set
            {
                SetProperty(ref _selectedProduct, value);
                if (value != null)
                {
                    ProductName = value.ProductName;
                    ProductId = value.ProductCode;
                    SpecificationModel = value.Specification;
                    Unit = value.UnitName;
                    ProductType = value.ProductTypeName;
                }
            }
        }

        public BomDto SelectedBom
        {
            get => _selectedBom;
            set => SetProperty(ref _selectedBom, value);
        }

        public string Annex
        {
            get => _annex;
            set => SetProperty(ref _annex, value);
        }

        public string UploadedFileName
        {
            get => _uploadedFileName;
            set => SetProperty(ref _uploadedFileName, value);
        }

        #endregion

        #region 命令

        public RelayCommand SaveCommand { get; }
        public RelayCommand CancelCommand { get; }
        public RelayCommand SelectProductCommand { get; }
        public RelayCommand SelectBomCommand { get; }
        public RelayCommand ClearBomCommand { get; }
        public RelayCommand UploadFileCommand { get; }

        #endregion

        #region 方法

        private bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(PlanId) &&
                   !string.IsNullOrWhiteSpace(PlanName) &&
                   SelectedProduct != null &&
                   PlanNums > 0 &&
                   StartTime.HasValue &&
                   EndTime.HasValue &&
                   NeedTime.HasValue &&
                   StartTime <= EndTime; // 开工时间不能晚于完工时间
        }

        private bool CanSelectBom()
        {
            return SelectedProduct != null;
        }

        private void SelectProduct()
        {
            try
            {
                var productWindow = new ProductViewWindow();
                productWindow.Owner = System.Windows.Application.Current.MainWindow;

                if (productWindow.ShowDialog() == true)
                {
                    var productViewModel = productWindow.DataContext as ProductViewModel;
                    if (productViewModel?.SelectedProduct != null)
                    {
                        SelectedProduct = productViewModel.SelectedProduct;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择产品失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SelectBom()
        {
            try
            {
                var bomSelectionWindow = new BomSelectionWindow();
                bomSelectionWindow.Owner = System.Windows.Application.Current.MainWindow;

                if (bomSelectionWindow.ShowDialog() == true)
                {
                    var selectedBom = bomSelectionWindow.SelectedBom;
                    if (selectedBom != null)
                    {
                        SelectedBom = selectedBom;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择BOM失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ClearBom()
        {
            SelectedBom = null;
        }

        private async Task SaveProductPlanAsync()
        {
            try
            {
                if (!CanSave())
                {
                    MessageBox.Show("请填写所有必填字段", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 构建新增生产计划的DTO
                var createDto = new CreateUpdateProductionPlanDto
                {
                    // 基础信息
                    Plan_Id = PlanId?.Trim(),
                    Plan_Name = PlanName?.Trim(),
                    OrderNums = 0, // 设置默认值，避免数据库 NOT NULL 约束错误
                    FromType = FromType,
                    
                    // 产品信息（从选择的产品自动填充）
                    ProductId = SelectedProduct?.Id,
                    ProductName = SelectedProduct?.ProductName,
                    Product_Id = SelectedProduct?.ProductCode,
                    SpecificationModel = SpecificationModel?.Trim(),
                    PoductType = SelectedProduct?.ProductTypeName,
                    Unit = Unit?.Trim(),
                    
                    // 计划信息
                    PlanNums = PlanNums,
                    StartTime = StartTime,
                    EndTime = EndTime,
                    NeedTime = NeedTime,
                    
                    // 其他信息
                    Remark = Remark?.Trim(),
                    Annex = Annex?.Trim(),
                    BomId = SelectedBom?.Id, // 从选择的BOM获取BomId
                    Status = 0 // 默认状态
                };

                // 验证关键字段
                if (!createDto.ProductId.HasValue || createDto.ProductId.Value <= 0)
                {
                    MessageBox.Show("产品ID无效，请重新选择产品", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!createDto.PlanNums.HasValue || createDto.PlanNums.Value <= 0)
                {
                    MessageBox.Show("计划数量必须大于0", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(createDto.Plan_Id))
                {
                    MessageBox.Show("计划编号不能为空", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(createDto.Plan_Name))
                {
                    MessageBox.Show("计划名称不能为空", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 调用ProductPlanService的AddProductPlanAsync方法
                var result = await _productPlanService.AddProductPlanAsync(createDto);

                // 显示成功消息
                MessageBox.Show("新增生产计划成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                
                // 关闭窗口并返回成功状态
                CloseWindow?.Invoke(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"新增生产计划失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(false);
        }

        private async Task UploadFileAsync()
        {
            try
            {
                // 打开文件选择对话框
                var openFileDialog = new OpenFileDialog
                {
                    Title = "选择要上传的文件",
                    Filter = "所有支持的文件|*.docx;*.xls;*.xlsx;*.pdf;*.rar;*.zip;*.png;*.jpg;*.jpeg|Word文档|*.docx|Excel文件|*.xls;*.xlsx|PDF文件|*.pdf|压缩文件|*.rar;*.zip|图片文件|*.png;*.jpg;*.jpeg|所有文件|*.*",
                    Multiselect = false
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    var filePath = openFileDialog.FileName;
                    var fileName = Path.GetFileName(filePath);
                    
                    // 检查文件是否存在
                    if (!File.Exists(filePath))
                    {
                        MessageBox.Show("选择的文件不存在，请重新选择", "文件错误", 
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    
                    // 检查文件大小（限制为50MB）
                    var fileInfo = new FileInfo(filePath);
                    if (fileInfo.Length > 50 * 1024 * 1024) // 50MB
                    {
                        MessageBox.Show("文件大小不能超过50MB，请选择较小的文件", "文件过大", 
                            MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    // 上传文件到服务器
                    using var fileStream = File.OpenRead(filePath);
                    var content = new MultipartFormDataContent();
                    var fileContent = new StreamContent(fileStream);
                    content.Add(fileContent, "file", fileName);

                    var response = await _httpClient.PostAsync("UploadFile/UploadTempFile", content);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        
                        // 解析JSON响应
                        using var jsonDoc = JsonDocument.Parse(responseContent);
                        var root = jsonDoc.RootElement;
                            
                        if (root.TryGetProperty("path", out var pathElement))
                        {
                            var uploadedFilePath = pathElement.GetString();
                            Annex = uploadedFilePath;
                            UploadedFileName = fileName;
                            
                            MessageBox.Show($"文件上传成功！\n文件名: {fileName}", "上传成功", 
                                MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            MessageBox.Show("服务器响应格式错误", "上传失败", 
                                MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"文件上传失败: {response.StatusCode} - {errorContent}", "上传失败", 
                            MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"文件上传失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion
    }
} 